<script lang="ts">
    import { onDestroy, onMount } from "svelte";
    import { CountUp as CU } from "./countUpLib";
    import { useClassList } from "../utils/useClassList";
    import type { CountUpProps } from "./CountUp";

    const props: CountUpProps = $props();
    const startVal = props.start ?? 0;
    let target: any;
    let instance: any;

    onMount(() => {
        instance = new CU(target, props.value, {
            startVal: startVal,
            duration: props.duration ?? 2,
            decimalPlaces: props.decimal ?? 0,
            useGrouping: props.useGrouping ?? true,
            useEasing: props.useEasing ?? true,
            separator: props.separator ?? ",",
            formattingFn: props.formattingFn,
            prefix: props.prefix ?? "",
            suffix: props.suffix ?? "",
            onCompleteCallback: onComplete,
        });
        if (!instance.error) {
            start();
        } else {
            console.error(instance.error);
        }
    });

    onDestroy(() => {
        instance = null;
    });

    const onComplete = () => {
        props.onend?.();
    };

    export const start = () => {
        instance && instance.start();
    };

    export const update = (val: number) => {
        instance && instance.update(val);
    };

    export const pauseResume = () => {
        instance && instance.pauseResume();
    };

    $effect(() => {
        update(props.value);
    });

    export const reset = () => {
        instance && instance.reset();
    };

    const classList = $derived(useClassList(props, "cm-count-up"));
</script>

<span class={classList} style={props.style} bind:this={target}></span>
